<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('字典名称')" prop="dictName">
            <el-input v-model="form.dictName" :placeholder="$t('字典名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('字典类型')" prop="dictType">
            <el-input v-model="form.dictType" :placeholder="$t('字典类型')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('状态')" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t("新增") }}</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="form.dataList"
        border
        class="formTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column width="40" type="selection" align="center" />
        <el-table-column width="120" :label="$t('排序')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dataList.' + scope.$index + '.dictSort'" :rules="rules.dictSort">
              <el-input-number v-model="scope.row.dictSort" controls-position="right" :min="0" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字典标签')">
          <template slot-scope="scope">
            <el-form-item
              :prop="'dataList.' + scope.$index + '.dictLabel'"
              :rules="rules.dictLabel"
            >
              <el-input v-model="scope.row.dictLabel" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字典键值')">
          <template slot-scope="scope">
            <el-form-item
              :prop="'dataList.' + scope.$index + '.dictValue'"
              :rules="rules.dictValue"
            >
              <el-input v-model="scope.row.dictValue" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column width="80" :label="$t('状态')" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
            />
          </template>
        </el-table-column>
        <el-table-column>
          <span slot="header">
            {{ $t('关联字典') }}
            <el-tooltip :content="$t('关联的二级字典')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <template slot-scope="scope">
            <el-select v-model="scope.row.childDict" clearable filterable :placeholder="$t('请选择')">
              <el-option
                v-for="dict in dictOptions"
                :key="dict.dictType"
                :label="$t(dict.dictName)"
                :value="dict.dictType"
              >
                <span style="float: left">{{ $t(dict.dictName) }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :maxlength="200" show-word-limit />
          </template>
        </el-table-column>

        <el-table-column
          width="50"
          :label="$t('操作')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
      style="text-align: right;width: 100%;"
    >
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button type="primary" @click="submitForm()">{{ $t("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
  // eslint-disable-next-line no-unused-vars
  import {
    delData
  } from '@/api/system/dict/data'
  import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
  import { listType } from '@/api/system/dict/type'
  import elDragDialog from '@/directive/el-drag-dialog'
  import { getAddSysDict } from '@/api/system/desform/data/onlCgformFieldData'
  export default {
    // name: 'Data',
    directives: { elDragDialog },
    props: {
      dictIdChild: {
        type: String,
        default: null
      }
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,

        // 状态数据字典
        statusOptions: [],
        // 类型数据字典
        typeOptions: [],
        // 字典信息
        dictOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dictName: undefined,
          dictType: undefined,
          status: undefined
        },
        // 表单参数
        form: {
          // 字典ID
          id: undefined,
          // 字典类型
          dictType: undefined,
          // 字典名称
          dictName: undefined,
          // 主表状态
          status: '0',
          // 备注
          remark: undefined,
          // 字典表格数据
          dataList: []
        },
        // 是否已保存
        isAdd: false,
        // 表单配置数据
        onlIndex: 0,
        // 表单校验
        rules: {
          dictName: [
            { required: true, message: this.$t('必填信息'), trigger: 'blur' }
          ],
          dictType: [
            { required: true, message: this.$t('必填信息'), trigger: 'blur' }
          ],
          dictLabel: [
            { required: true, message: this.$t('必填信息'), trigger: 'blur' }
          ],
          dictValue: [
            { required: true, message: this.$t('必填信息'), trigger: 'blur' }
          ],
          dictSort: [
            { required: true, message: this.$t('必填信息'), trigger: 'blur' }
          ]
        }
      }
    },
    // watch: {
    //   dictIdChild: {
    //     immediate: true, // 很重要！！！
    //     handler(val) {
    //       this.dictIdChild = !val ? {} : val
    //       const dictId = this.dictIdChild
    //       this.getType(dictId)
    //     }
    //   }
    // },

    created() {
      this.getTypeList()
      this.getDicts('sys_normal_disable').then((response) => {
        this.statusOptions = response.data
      })
      /** 查询字典下拉列表 */
      getDictOptionselect().then((response) => {
        this.dictOptions = response.data
      })
    },
    methods: {
      /** 查询字典类型详细 */
      // getType(dictId) {
      //   getType(dictId).then((response) => {
      //     this.queryParams.dictType = response.data.dictType
      //     this.form.id = response.data.id
      //     this.form.dictName = response.data.dictName
      //     this.form.dictType = response.data.dictType
      //     this.getList()
      //   })
      // },
      /** 查询字典类型列表 */
      getTypeList() {
        listType().then((response) => {
          this.typeOptions = response.rows
        })
      },
      /** 查询字典数据列表 */
      init(index) {
        this.onlIndex = index
        this.loading = true
        this.reset()
        this.loading = false
      },
      // 字典状态修改 0启用 1停用
      // handleStatusChange(row) {
      //   if (row.status === '0') {
      //     row.status = '1'
      //   }
      //   if (row.status === '1') {
      //     row.status = '0'
      //   }
      // },

      /** 删除按钮操作 */
      handleDel(index, row) {
        console.log(index, row)
        // eslint-disable-next-line eqeqeq
        if (row.id !== null && row.id !== undefined && row.id !== '') {
          this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
            .then(function() {
              return delData(row.id)
            })
            .then(() => {
              this.form.dataList.splice(index, 1)
              this.msgSuccess(this.$t('删除成功'))
            })
            .catch(function() {})
          // eslint-disable-next-line eqeqeq
        } else {
          this.form.dataList.splice(index, 1)
        }
      },
      // 数据状态字典翻译
      statusFormat(row, column) {
        console.log(column)
        return this.selectDictLabel(this.statusOptions, row.status)
      },
      // 取消按钮
      cancel() {
        this.$parent.$parent.viewDictOpen = false
        // this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          // 字典ID
          id: undefined,
          // 字典类型
          dictType: undefined,
          // 字典名称
          dictName: undefined,
          status: '0',
          remark: undefined,
          // 字典表格数据
          dataList: []
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd() {
        const row = {
          dictCode: '',
          dictLabel: '',
          dictValue: '',
          dictSort: this.form.dataList.length + 1,
          status: '0',
          remark: ''
        }
        this.form.dataList.push(row)
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.dictCode)
        this.multiple = !selection.length
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            getAddSysDict(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('新增成功'))
                  this.isAdd = true
                  this.closeForm()
                } else {
                  this.msgError(response.msg)
                }
              })
          } else {
            this.locationError(document)
          }
        })
      },
      // 关闭form页面
      closeForm() {
        // 关闭form页面遮罩层
        this.loading = false
        // 关闭form页面
        if (this.$parent.$parent.dictOpen !== undefined) {
          this.$parent.$parent.dictOpen = false
        }
        // 刷新list页面
        if (this.$parent.$parent.getList !== undefined) {
          this.$parent.$parent.getList()
        }
        // 刷新表单配置页面 关联数据集合
        if (this.$parent.$parent.getDict !== undefined) {
          this.$parent.$parent.getDict()
          if (this.isAdd) {
            this.$parent.$parent.tableData[this.onlIndex].fieldDefaultValue = this.form.dictType
          }
        }
      }
    }
  }
</script>
